package at.hockey.ticker;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class HTService extends Service {
	private final String TAG = this.getClass().getSimpleName();
	
	public static final String NEW_STATUS_INTENT = "at.hockey.ticker.NEW_STATUS";
	public static final String NEW_SVCSTAT_INTENT = "at.hockey.ticker.NEW_SVCSTAT";
    static final String RECEIVE_SVCSTAT_NOTIFICATIONS = "at.hockey.ticker.RECEIVE_SVCSTAT_NOTIFICATIONS";
	
	static final int DELAY = 10000;     //60000; // a minute
	private boolean runFlag = false;
	private Updater updater;
	private HTApplication HTapp;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		
		this.HTapp = (HTApplication) getApplication();
		this.updater = new Updater();
	    
		Log.d(TAG, "onCreated");
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	    
		this.runFlag = false;
	    this.updater.interrupt();
	    this.updater = null;
	    this.HTapp.setServiceRunning(false);
	    
	    this.sendnotify();
		
	    Log.d(TAG, "onDestroyed");
	}

   private void sendnotify() {
	   Intent intent;
	   
	   intent = new Intent(NEW_SVCSTAT_INTENT);
	   this.sendBroadcast(intent, RECEIVE_SVCSTAT_NOTIFICATIONS);
	   Log.d(TAG, "sendnotify: send Broadcast - new SVCSTAT");	   
   }
	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
	    
		if (!runFlag) {
			this.runFlag = true;
		    this.updater.start();
		    this.HTapp.setServiceRunning(true);
		    Log.d(TAG, "onStartCommand -> fist time");
		}
		else {
		    Log.d(TAG, "onStartCommand -> already running");			
		}
	    return START_STICKY; // TODO check
	}

	  /**
	   * Thread that performs the actual update from the online service
	   */
	  private class Updater extends Thread {
	    static final String RECEIVE_GAME_NOTIFICATIONS = "at.hockey.ticker.RECEIVE_GAME_NOTIFICATIONS";
	    Intent intent;
		  
		  
	    public Updater() {
	      super("UpdaterService-Updater");  // set name for debugging
	    }

	    @Override
	    public void run() { // java thread needs run
	      HTService updaterService = HTService.this;  // simply creates a reference to our service
	      while (updaterService.runFlag) {
	        Log.d(TAG, "Updater running in background thread");
	        try {
	          // TODO Some work goes here...
	        	
	        	HTapp.DataBoxInserter("Affenmann_");
	            
	        	intent = new Intent(NEW_STATUS_INTENT);
	            updaterService.sendBroadcast(intent, RECEIVE_GAME_NOTIFICATIONS);
	            
	          Log.i(TAG, "New data arrived");
	          Thread.sleep(DELAY);
	        } catch (InterruptedException e) {  // signal interrupt() to the thread...
	          updaterService.runFlag = false;
	        }
	      }
	    }
	  } // Updater
	
}
